package com.natasha.pins.view.activity;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.natasha.pins.R;
import com.natasha.pins.bh.pinsmaster.PinsMasterBH;
import com.natasha.pins.data.bean.PinsMasterBean;
import com.natasha.pins.util.Constants;

public class PinsEditActivity extends Activity {
	
	private EditText etEPTitle;
	private EditText etEPStory;
	private Button btnSave;
	private Button btnWhenDt;
	private Button btnWhenTime;
	private Calendar localCalendar;

	private PinsMasterBH pinsMasterBH;
	private Long pinId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		pinsMasterBH = new PinsMasterBH(this);
		
		setContentView(R.layout.pin_edit);
		localCalendar = Calendar.getInstance();
		
		etEPTitle = (EditText) findViewById(R.id.etEPTitle);
		etEPStory = (EditText) findViewById(R.id.etEPStory);
		btnWhenDt = (Button) findViewById(R.id.bEPWhenDt);
		btnWhenTime = (Button) findViewById(R.id.bEPWhenTime);
		btnSave = (Button) findViewById(R.id.btFEPSave);
		
		pinId = savedInstanceState != null ? savedInstanceState.getLong(PinsMasterBean.NAME_PMID) : null;
		Log.d(Constants.LOG_DEBUG, this.getClass().getName() + ".onCreate - pinId : " + pinId);
		/*if(getIntent() != null ){
			Bundle extras = getIntent().getExtras();
			int rowId = extras!=null ? extras.getInt("RowId") : -1;
		}*/
		
		registerButtonListeners();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent){
		super.onActivityResult(requestCode, resultCode, intent);
		//TODO: Reload the list here
		Log.d(Constants.LOG_DEBUG, this.getClass().getName() + ".onActivityResult : ");
	}
	
	private void registerButtonListeners(){
		
		btnWhenDt.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(Constants.DATE_PICKER_DIALOG);
			}
		});
		
		btnWhenTime.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(Constants.TIME_PICKER_DIALOG);
			}
		});
		
		btnSave.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				saveState();
				setResult(RESULT_OK);
				Toast.makeText(PinsEditActivity.this, 
						getString(R.string.task_saved_message), 
						Toast.LENGTH_SHORT).show();
				finish();
				//TODO validate input
				/*
				AlertDialog.Builder builder = new AlertDialog.Builder(PinsEditActivity.this);
				builder.setMessage("Are you sure?")
						.setCancelable(false)
						.setPositiveButton("Yes", 
								new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Perform actions to positive response.
									}
								})
						.setNegativeButton("No", 
								new DialogInterface.OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.cancel();
									}
								})
						;
				builder.create().show();*/
			}
		});
		
		updateDateButtonText();
		updateTimeButtonText();
	}
	
	@Override
	protected Dialog onCreateDialog(int id){
		switch (id) {
		case Constants.DATE_PICKER_DIALOG:
			return showDatePicker();
		case Constants.TIME_PICKER_DIALOG:
			return showTimePicker();
		}
		return super.onCreateDialog(id);
	}
	
	private DatePickerDialog showDatePicker(){
		DatePickerDialog datePicker = new DatePickerDialog(PinsEditActivity.this, 
					new DatePickerDialog.OnDateSetListener() {
						
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							
							localCalendar.set(Calendar.YEAR, year);
							localCalendar.set(Calendar.MONTH, monthOfYear);
							localCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
							updateDateButtonText();
						}
					}
					, localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH), localCalendar.get(Calendar.DAY_OF_MONTH));
		return datePicker;
	}
	
	private TimePickerDialog showTimePicker(){
		TimePickerDialog timePicker = new TimePickerDialog(this, 
					new TimePickerDialog.OnTimeSetListener() {
						
						@Override
						public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
							localCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
							localCalendar.set(Calendar.MINUTE, minute);
							updateTimeButtonText();
						}
					}
					, localCalendar.get(Calendar.HOUR_OF_DAY), localCalendar.get(Calendar.MINUTE), true);
		return timePicker;
	}
	
	private void updateDateButtonText(){
		SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
		String dateForButton = dateFormat.format(localCalendar.getTime());
		btnWhenDt.setText(dateForButton);
	}
	
	private void updateTimeButtonText(){
		SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.TIME_FORMAT);
		String timeForButton = dateFormat.format(localCalendar.getTime());
		btnWhenTime.setText(timeForButton);	
	}
	
	private void saveState(){
		PinsMasterBean pin;
		String title = etEPTitle.getText().toString();
		String story = etEPStory.getText().toString();
		
		if(pinId == null){
			pin = new PinsMasterBean("Me", 0, new Date(localCalendar.getTime().getTime()), title, story, 0, "");		
			Log.d(Constants.LOG_DEBUG, this.getClass().getName() + ".saveState creating bean: " + pin);
			long id = pinsMasterBH.createPin(pin);
			if(id>0){
				pinId = id;
			}
		}
		else{
			pin = new PinsMasterBean("Me", pinId.intValue(), new Date(localCalendar.getTime().getTime()), title, story, 0, "");		
			Log.d(Constants.LOG_DEBUG, this.getClass().getName() + ".saveState updating bean: " + pin);
			pinsMasterBH.updatePin(pin);
		}
	}

	@Override
	protected void onPause(){
		super.onPause();
		pinsMasterBH.closeConnection();
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		pinsMasterBH.getConnection();
		setPinFromIntent();
		populateFields();
	}
	
	private void setPinFromIntent(){
		if(pinId == null){
			Bundle extras = getIntent().getExtras();
			pinId = extras!=null ? extras.getLong(PinsMasterBean.NAME_PMID) : null;
			
			Log.d(Constants.LOG_DEBUG, this.getClass().getName() + ".setPinFromIntent - pinId : " + pinId);
		}
	}
	
	private void populateFields(){
		PinsMasterBean bean;
		if(pinId != null){
			Cursor pin = pinsMasterBH.fetchPin(pinId);
			bean = new PinsMasterBean(pin);
			
			etEPTitle.setText(bean.getPmtitle());
			etEPStory.setText(bean.getPmdetail());
			localCalendar.setTime(bean.getPmwhendt());
			
		}
		updateDateButtonText();
		updateTimeButtonText();
	}
	/*
	private void populateFields(){
		if(pinId != null){
			Cursor pin = pinsMasterBH.fetchPin(pinId);
			startManagingCursor(pin);
			etEPTitle.setText(pin.getString(pin.getColumnIndexOrThrow(PinsMasterBean.NAME_PMTITLE)));
			etEPStory.setText(pin.getString(pin.getColumnIndexOrThrow(PinsMasterBean.NAME_PMDETAIL)));
			SimpleDateFormat dateTimeFormat = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
			java.util.Date date = null;
			try{
				String dateString = pin.getString(pin.getColumnIndexOrThrow(PinsMasterBean.NAME_PMWHENDT));
				date = dateTimeFormat.parse(dateString);
				localCalendar.setTime(date);
			}catch(ParseException e){
				Log.e(this.getClass().getName(), e.getMessage(), e);
			}
		}
		updateDateButtonText();
		updateTimeButtonText();
	}*/
	
	@Override
	protected void onSaveInstanceState(Bundle outState){
		super.onSaveInstanceState(outState);
		outState.putLong(PinsMasterBean.NAME_PMID, pinId);
	}
	
}
